<?php
// +----------------------------------------------------------------------
// | 登录验证中间件
// +----------------------------------------------------------------------
// | Author: myh
// +----------------------------------------------------------------------
namespace app\admin\middleware;

use app\common\service\SysMenuService;
use app\common\service\SysRoleService;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Auth
{
    public function handle($request, \Closure $next)
    {   
        try{
            $token = $request->header('token');
            $device = $request->header('device');
            if($device == 'admin' && $token){
                //解析token得到用户信息
                $userInfo = JWT::decode($token,new Key(config('app.jwt_code_admin'),'HS256'));
                //把部分用户信息保存到全局reqeust对象中
                $request->user = ['id'=>$userInfo->id,'account'=>$userInfo->account];

                //判断是否有权限访问
                // if(!$this->checkPermission($request,$userInfo)){
                //     return failure(config('error.er19')['code'],config('error.er19')['msg']);
                // }
            }else{
                return failure(config('error.er14')['code'],config('error.er14')['msg']);
            }
        }catch (\Exception $e) {
            return failure(config('error.er14')['code'],config('error.er14')['msg']);
        }

        return $next($request);
    }

    private function checkPermission($request,$userInfo){
        if($userInfo->root == 1){
            //超管直接返回true
            return true;
        }

        if(!$userInfo->roles){
            return false;
        }

        if(cache(ADMIN_PERMS_.$userInfo->id)){
            $perms = cache(ADMIN_PERMS_.$userInfo->id);
        }else{
            //根据角色获取菜单ID
            $authIds = SysRoleService::getAuths($userInfo->roles);
            //根据菜单ID获取权限标识，返回的是一个一维数组
            $perms = SysMenuService::getPerms($authIds);
            //保存到缓存中，避免每次查询数据库，注意这里的键值使用了用户ID进行区分
            cache(ADMIN_PERMS_.$userInfo->id,$perms);
        }
        
        if(count($perms) == 0) return false;
        
        //通过request对象获取当前访问的控制器名和方法名，也就是权限标识
        $current = $request->controller().'/'.$request->action();
        //判断标识是否存在于当前用户中
        if(!in_array($current,$perms)){
            return false;
        }

        return true;
    }
}